package cn.slb.im.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.slb.im.common.utils.PageUtils;
import cn.slb.im.common.utils.Query;

import cn.slb.im.user.dao.DeptDao;
import cn.slb.im.user.entity.DeptEntity;
import cn.slb.im.user.service.DeptService;


@Service("deptService")
public class DeptServiceImpl extends ServiceImpl<DeptDao, DeptEntity> implements DeptService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DeptEntity> page = this.page(
                new Query<DeptEntity>().getPage(params),
                new QueryWrapper<DeptEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<DeptEntity> listTree(Map<String, Object> params) {
        // 1 查询所有部门
        List<DeptEntity> deptList = this.list(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getIsDelete,0));
        // 2 组装树结构
        return deptList.stream().filter(d -> d.getParentId().equals(0L)).map(d -> {
            d.setChildren(buildChildren(d, deptList));
            return d;
        }).sorted((d1,d2)->{
            return (d2.getSort()-d1.getSort());
        }).collect(Collectors.toList());
    }

    /**
     * 递归构建子部门
     * @param dept
     * @param deptList
     * @return
     */
    private List<DeptEntity> buildChildren(DeptEntity dept, List<DeptEntity> deptList) {
        return deptList.stream().filter(d->d.getParentId().equals(dept.getId())).map(d->{
            d.setChildren(buildChildren(d,deptList));
            d.setParentName(dept.getDeptName());
            return d;
        }).sorted((d1,d2)->{
            return (d2.getSort()-d1.getSort());
        }).collect(Collectors.toList());
    }

    @Override
    public void deleteByIds(Long[] ids) {
        List<DeptEntity> list = new ArrayList<>();
        Arrays.asList(ids).stream().forEach(id->{
            DeptEntity entity = new DeptEntity();
            entity.setId(id);
            entity.setIsDelete(1);
            list.add(entity);
        });
        this.updateBatchById(list);
    }
}
